<template>
  <div>
    <a-modal
      :title='this.title'
      :visible='this.visible'
      :width='660'
      @cancel='cancel'
      @ok='ok'
    >
      <a-form :form='form' v-bind='formItemLayout'>
        <a-form-item label='城市名称'>
          <a-input @blur="handleChangeName" v-decorator='this.validator1.city' />
        </a-form-item>
        <a-form-item label='城市编码'>
          <a-input v-decorator='this.validator1.cityCode' />
        </a-form-item>
        <a-form-item label='区域点集'>
          <a-input v-decorator='this.validator1.polygonText' />
        </a-form-item>
        <a-form-item label='父级城市'>
          <!-- <a-select
                v-decorator='this.validator1.provinceCode'
              >
                <a-select-option v-for='item in this.cityInfos' :key='item.cityCode' :value='item.cityCode'>{{ item.city }}</a-select-option>

              </a-select> -->
          <!-- <a-input
            v-decorator='this.validator1.provinceCode'
            @input='provinceCodeChange'
          />
          <div v-if="cityInfos.length>0">
            <span v-for="(item, index) in cityInfos" :key="item.numberId" @click="provinceCodeClick(index)">{{item.mergerName}}</span>
          </div> -->
          <a-select
            show-search
            :value="value"
            placeholder="请输入父级城市名搜素"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            v-decorator='this.validator1.province'
            @search="fetchUser"
            @change="handleChange"
          >
            <a-select-option v-for="d in data" :key="d.value">
              {{ d.text }}
            </a-select-option>
          </a-select>
<!--            <a-select
              mode="multiple"
              label-in-value
              :value="value"
              style="width: 100%"
              :filter-option="false"
              :not-found-content="fetching ? undefined : null"
              @search="fetchUser"
              @change="handleChange"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option v-for="d in data" :key="d.value">
                {{ d.text }}
              </a-select-option>
            </a-select>-->
        </a-form-item>
        <a-form-item label='父级编码'>
          <a-input v-decorator='this.validator1.provinceCode' />
        </a-form-item>
        <a-form-item label='标记信息'>
          <a-input v-decorator='this.validator1.remarks' />
        </a-form-item>
        <a-form-item label='所属层级'>
          <a-input v-decorator='this.validator1.levelType' />
        </a-form-item>
        <a-form-item label='城市全称'>
          <a-input
            v-decorator='this.validator1.mergerName'
            readonly='readOnly'
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <modal
      ref='flowModalForm'
      :flowTitle='this.flowTitle'
      :flowVisible='this.flowVisible'
      @cancel='handleCancel'
      @ok='handleOk'
    />
  </div>
</template>

<script>
import aModal from '@/common/modal'
import modal from '../../needsManage/components/flowModal'
import { GETCITYINFOS, INSERTCITYINFOS } from '@/../static/js/apis.js'
import { cityInfosForm } from '@/../static/js/formValidators.js'
import { TreeSelect } from 'ant-design-vue'
import debounce from 'lodash/debounce'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
export default {
  inject: ['reload'], // 注入App里的reload方法
  name: 'TaskModal',
  props: [
    'title',
    'visible',
    'demandName',
    'demandId',
    'demandYear',
    'demandClassify',
    'tabType',
    'flowTitle',
    'flowVisible'
  ],
  components: {
    aModal,
    modal
  },
  data() {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      validator1: cityInfosForm,
      cityInfos: [],
      SHOW_PARENT,
      keyWords: '',
      restaurants: [],
      state: '',
      timeout: null,
      modalFlowVisible: false,
      data: [],
      value: [],
      fetching: false
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'productTaskForm' })
  },
  computed: {
    headers() {
      return {
        token: localStorage.getItem('token')
      }
    }
  },
  methods: {
    handleOk(e) {
      this.modalFlowVisible = false
    },
    handleCancel(e) {
      this.see = false
      this.modalFlowVisible = false
    },

    callback(key) {
      this.tabType = key
    },
    getStaticData() {
      GETCITYINFOS(
        { keyWords: this.keyWords, page: 1, limit: 9999999 },
        (res) => {
          this.cityInfos = res.list
        }
      )
    },
    provinceCodeClick(index) {
      const self = this
      this.$nextTick(() => {
        self.form.setFieldsValue({
          provinceCode: self.cityInfos[index].cityCode,
          levelType: Number(self.cityInfos[index].levelType)
        })
      })
    },
    ok(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.provinceCode = this.value[0].key
          console.log('执行了ok方法', values, this.value)
          INSERTCITYINFOS(values, res => {
            if (res.code === '200') {
              this.$message.success(res.message)
              this.$emit('cancel', e)
              this.getStaticData()
            } else this.$message.error(res.messsage)
          })
        } else {
          this.$message.error('失败')
        }
      })
    },
    /* 关闭modal */
    cancel(e) {
      this.form.resetFields()
      this.see = false
      this.$emit('cancel', e)
      //  this.see=false
    },
    fetchUser(value) {
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.data = []
      this.fetching = true
      GETCITYINFOS(
        { keyWords: value, page: 1, limit: 9999999 },
        (res) => {
          if (fetchId !== this.lastFetchId) {
            // for fetch callback order
            return
          }
          const data = res.list.map(item => ({
            text: `${item.city}`,
            value: `${item.city}`,
            mergerName: `${item.mergerName}`,
            levelType: `${item.levelType}`,
            cityCode: `${item.cityCode}`
          }))
          this.data = data
          console.log(this.data)
          this.cityInfos = data
          this.fetching = false
        }
      )
    },
    handleChangeName(event) {
      const value = event.target.value
      console.log(value)
      const fkey = this.form.getFieldValue('province')

      console.log(fkey)
      console.log(this.data)
      const ele = this.data.filter(i => i.value === fkey).length > 0 ? this.data.filter(i => i.value === fkey)[0] : null
      if ( !ele){
        console.log("find nothing")
        return
      }
      const mergerName = ele.mergerName
      console.log('mergerName：', mergerName)
      this.form.setFieldsValue({
        mergerName: `${mergerName},${value}`
      })
    },
    handleChange(value) {
      console.log('value :' + value)
      const ele = this.data.filter(i => i.value === value).length > 0 ? this.data.filter(i => i.value === value)[0] : null
      if (!ele) {
        return
      }
      const levelType = Number(ele.levelType) + 1
      const city = this.form.getFieldValue('city') ? this.form.getFieldValue('city') : ''
      console.log(this.form.getFieldValue('city'))

      console.log(this.data)
      const mergerName = ele.mergerName
      console.log('mergerName：', mergerName)
      this.form.setFieldsValue({
        levelType: levelType,
        mergerName: `${mergerName},${city}`,
        provinceCode: ele.cityCode
      })
      Object.assign(this, {
        value,
        /*data: [],*/
        fetching: false
      })
    }
  },
  created() {
    this.getStaticData()
  },

}
</script>

<style scoped>

</style>
